package dynamicprogramming;

/**
 * @Author: 海琳琦
 * @Date: 2022/3/2 18:03
 * https://leetcode-cn.com/problems/unique-paths-ii/
 */
public class UniquePathsWithObstacles {

    /**
     * dp[i][j]：表示到达i,j位置经过多少种不同的路径
     * 递推公式：dp[i][j] = dp[i-1][j] + dp[i][j-1];
     * 初始化：dp[i][0] = 1; dp[0][j] = 1;
     *
     * 遇到障碍dp[i][j]保持0就可以了
     * 也有一些小细节，例如：初始化的部分，很容易忽略了障碍之后应该都是0的情况。
     * @param obstacleGrid
     * @return
     */
    public static int uniquePathsWithObstacles(int[][] obstacleGrid) {
        //行
        int m = obstacleGrid.length;
        //列
        int n = obstacleGrid[0].length;
        if (obstacleGrid[0][0] == 1 || obstacleGrid[m - 1][n - 1] == 1) {
            return 0;
        }
        int[][] dp = new int[m][n];
        //初始化
        for (int i = 0; i < m; i++) {
            if (obstacleGrid[i][0] != 1) {
                dp[i][0] = 1;
            } else {
                break;
            }
        }
        for (int j = 0; j < n; j++) {
            if (obstacleGrid[0][j] != 1) {
                dp[0][j] = 1;
            } else {
                break;
            }
        }
        for (int i = 1; i < m; i++) {
            for (int j = 1; j < n; j++) {
                if (obstacleGrid[i][j] != 1) {
                    dp[i][j] = dp[i-1][j] + dp[i][j-1];
                }
            }
        }
        return dp[m - 1][n - 1];
    }

    public static void main(String[] args) {
        int[][] obstacles = {{0,0},{1,1},{0,0}};
        int i = uniquePathsWithObstacles(obstacles);
        System.out.println(i);
    }
}
